﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Xml;
using System.IO;
using System.Data.SqlClient;
using System.Data;

public partial class weixin : System.Web.UI.Page
{
    const string Token = "jinhuan";//你的token


    protected void Page_Load(object sender, EventArgs e)
    {

        string postStr = "";



        if (Request.HttpMethod.ToLower() == "post")//不为空，说明已验证服务器资源
        {

            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;

            byte[] b = new byte[s.Length];

            s.Read(b, 0, (int)s.Length);

            postStr = System.Text.Encoding.UTF8.GetString(b);

            if (!string.IsNullOrEmpty(postStr))
            {

                //ResponseMsg(postStr);

                Response.Write(ResponseMsg(postStr));

                Response.End();

            }

            //WriteLog("postStr:" + postStr);

        }

        else//为空，说明未验证服务器资源
        {

            Valid();

        }

    }

    /// <summary>

    /// 验证微信签名

    /// </summary>

    /// * 将token、timestamp、nonce三个参数进行字典序排序

    /// * 将三个参数字符串拼接成一个字符串进行sha1加密

    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。

    /// <returns></returns>

    private bool CheckSignature()
    {

        string signature = "";
        if (Request.QueryString["signature"] != null)
        {
            signature = Request.QueryString["signature"].ToString();
        }


        string timestamp = "";
        if (Request.QueryString["timestamp"] != null)
        {
            timestamp = Request.QueryString["timestamp"].ToString();
        }


        string nonce = "";
        if (Request.QueryString["nonce"] != null)
        {
            nonce = Request.QueryString["nonce"].ToString();
        }


        string[] ArrTmp = { Token, timestamp, nonce };

        Array.Sort(ArrTmp);     //字典排序

        string tmpStr = string.Join("", ArrTmp);

        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

        tmpStr = tmpStr.ToLower();

        if (tmpStr == signature)
        {

            return true;

        }

        else
        {

            return false;

        }

    }

    private void Valid()
    {

        string echoStr = "";
        if (Request.QueryString["echoStr"] != null)
        {
            echoStr = Request.QueryString["echoStr"].ToString();
        }


        if (CheckSignature())
        {

            if (!string.IsNullOrEmpty(echoStr))
            {

                Response.Write(echoStr);//返回给微信

                Response.End();

            }

        }

    }

    /// <summary>

    /// 返回信息结果(微信信息返回)

    /// </summary>

    /// <param name="weixinXML"></param>

    private string ResponseMsg(string weixinXML)
    {
        Datacon dataconn = new Datacon();
        Datacommand datacom = new Datacommand();
        seleData ddsj = new seleData();
        SqlConnection cn = dataconn.getcon();
        cn.Open();

        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.TableMappings.Add("Table", "system_config");

        SqlCommand command = new SqlCommand("select * from system_config", cn);
        command.CommandType = CommandType.Text;
        adapter.SelectCommand = command;
        DataSet dataSet = new DataSet("system_config");
        adapter.Fill(dataSet);
        DataTable system_config = dataSet.Tables["system_config"];

        string sql = "select * from system_config";
        SqlCommand myCommand = new SqlCommand(sql, cn);


        string resxml = "";

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(weixinXML);

        XmlElement rootElement = doc.DocumentElement;

        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

        //RequestXML requestXML = new RequestXML();

        string ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;

        string FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;

        string CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;

        string MsgType1 = MsgType.InnerText;

        string yichuli = "wei";//记录是否已处理

        dataconn.WriteLogclass("第一" + MsgType1);

        if (MsgType1 == "text")
        {

            string Content = rootElement.SelectSingleNode("Content").InnerText;


            WriteLog("wei" + Content);


            //判断是否为绑定业务
            sql = "select * from guanzhuqingkuang where weixinghao='" + FromUserName + "'";
            WriteLog(sql);
            myCommand.CommandText = sql;
            myCommand.Clone();
            cn.Close();
            cn.Open();
            WriteLog("开始执行" + sql);
            SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            WriteLog("执行完成" + sql);
            if (reader.Read())
            {
                //WriteLog("开始执行" + reader["zhuixingbiaozhi"].ToString());
                if (reader["zhuixingbiaozhi"].ToString() != "0")//不为0，说明是绑定流程
                {
                    if (reader["zhuixingbiaozhi"].ToString() == "1")//等待选择是通过绑定码绑定还是通过水表号+电话号码
                    {
                        if (Content == "0")//退出绑定流程
                        {
                            datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=0 where weixinghao='" + FromUserName + "'");

                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[已退出绑定流程，如需绑定请重新点击绑定菜单。\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                        if (Content == "1")//选择通过绑定码绑定  返回发送绑定码过来
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["ztgbdmhf"].ToString() + "\n\n" + system_config.Rows[0]["bangdingtishshuomingizuihou"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=2 where weixinghao='" + FromUserName + "'");

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                        if (Content == "2")//选择通过水表号+电话号码绑定  返回先发送水表号过来
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["xfssbhts"].ToString() + "\n\n" + system_config.Rows[0]["bangdingtishshuomingizuihou"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=3 where weixinghao='" + FromUserName + "'");

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                        //不是0、1和2时回复
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[应该回复数字【1】或【2】，或回复数字【0】退出绑定流程\n\n请回复数字【1】 " + system_config.Rows[0]["bdsbdhwzsm"].ToString() + "\n" + "请回复数字【2】 " + system_config.Rows[0]["bdssbhhdhumsm"].ToString() + "\n\n" + system_config.Rows[0]["bangdingtishshuomingizuihou"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        //datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=3 where weixinghao='" + FromUserName + "'");

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;


                    }

                    if (reader["zhuixingbiaozhi"].ToString() == "2")//等待回复绑定码绑定
                    {
                        //判断绑定码是否正确
                        reader.Close();
                        cn.Close();
                        cn.Open();
                        sql = "select * from jibenzhiliao where bangdingma='" + Content + "'";
                        myCommand.CommandText = sql;
                        reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                        if (reader.Read())//如果找到，更新到数据库并回复成功和基本资料
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[绑定成功，请使用其他功能。\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            datacom.eccom("update jibenzhiliao set weixinghao='" + FromUserName + "' where bangdingma='" + Content + "'");
                            datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=0 where weixinghao='" + FromUserName + "'");
                            datacom.eccom("update yongshui set weixinghao='" + FromUserName + "'  where jbzlbbm=" + reader["id"].ToString());
                            WriteLog("update yongshui set weixinghao='" + FromUserName + "'  where jbzlbbm=" + reader["id"].ToString());
                            datacom.eccom("update yongshuilishi set weixinghao='" + FromUserName + "'  where jbzlbbm=" + reader["id"].ToString());
                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;
                        }
                        else
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[绑定失败，请重新点击菜单进行绑定。\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=0 where weixinghao='" + FromUserName + "'");

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                    }


                    if (reader["zhuixingbiaozhi"].ToString() == "3")//等待回复电话号码
                    {
                        //记录下水表号，提示输入电话号码
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["hfdhhm"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=4,shuibiaohao='" + Content + "' where weixinghao='" + FromUserName + "'");

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }

                    if (reader["zhuixingbiaozhi"].ToString() == "4")//等待回复电话号码绑定
                    {
                        //判断水表号+电话号码是否正确
                        //先取得已记录的水表号
                        reader.Close();
                        cn.Close();
                        cn.Open();
                        sql = "select * from guanzhuqingkuang where weixinghao='" + FromUserName + "'";
                        myCommand.CommandText = sql;
                        reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        if (reader.Read())
                        {
                            string sbh = reader["shuibiaohao"].ToString();
                            //判断水表号+电话号码是否合法
                            reader.Close();
                            cn.Close();
                            cn.Open();
                            sql = "select * from jibenzhiliao where shuibiaohao='" + sbh + "' and lianxidianhua='" + Content + "'";
                            myCommand.CommandText = sql;
                            reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                            if (reader.Read())//如果找到，更新到数据库并回复成功和基本资料
                            {
                                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[绑定成功，请使用其他功能。\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                                datacom.eccom("update jibenzhiliao set weixinghao='" + FromUserName + "' where shuibiaohao='" + sbh + "' and lianxidianhua='" + Content + "'");
                                datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=0 where weixinghao='" + FromUserName + "'");
                                datacom.eccom("update yongshui set weixinghao='" + FromUserName + "'  where jbzlbbm=" + reader["id"].ToString());
                                datacom.eccom("update yongshuilishi set weixinghao='" + FromUserName + "'  where jbzlbbm=" + reader["id"].ToString());

                                yichuli = "yi";

                                System.Web.HttpContext.Current.Response.Write(resxml);
                                cn.Close();
                                return resxml;
                            }
                            else
                            {
                                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[绑定失败，请重新点击菜单进行绑定。\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                                datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=0 where weixinghao='" + FromUserName + "'");

                                yichuli = "yi";

                                System.Web.HttpContext.Current.Response.Write(resxml);
                                cn.Close();
                                return resxml;

                            }
                        }
                    }


                    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["guanzhuhuifu"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                    yichuli = "yi";

                    System.Web.HttpContext.Current.Response.Write(resxml);
                    cn.Close();
                    return resxml;

                }

                //输入的是查询办事指南的文字，到数据库查询
                string bszn = "";
                WriteLog("bszn" + Content);
                bszn = ddsj.chabszn(Content, system_config.Rows[0]["urltou"].ToString() + system_config.Rows[0]["danweihao"].ToString());
                WriteLog("bsznjg" + Content);
                if (bszn != "")
                {
                    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[请点击了解详情\n\n" + bszn + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";
                    WriteLog(resxml);
                    System.Web.HttpContext.Current.Response.Write(resxml);

                    yichuli = "yi";

                    cn.Close();
                    return resxml;

                }



            }
            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["guanzhuhuifu"].ToString() + "]]></Content></xml>";
            WriteLog(resxml);
            System.Web.HttpContext.Current.Response.Write(resxml);
            yichuli = "yi三四三";
            yichuli = "yi";

            cn.Close();
            return resxml;

        }

        if (MsgType1 == "event")//订阅或取消订阅
        {
            string Event = rootElement.SelectSingleNode("Event").InnerText;
            if (Event == "subscribe")//订阅
            {
                resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["guanzhuhuifu"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";
                datacom.eccom("insert into guanzhuqingkuang(weixinghao,zhuixingbiaozhi,guanzhushijian) values ('" + FromUserName + "','0',getdate())");

                yichuli = "yi";

                System.Web.HttpContext.Current.Response.Write(resxml);
                cn.Close();
                return resxml;
            }
            if (Event == "unsubscribe")//取消订阅
            {
                resxml = "  ";

                datacom.eccom("update guanzhuqingkuang set quxiaoshijian=getdate() where id in (select  top 1  id from guanzhuqingkuang where weixinghao='" + FromUserName + "' order by id desc)");

                yichuli = "yi";

                System.Web.HttpContext.Current.Response.Write(resxml);
                cn.Close();
                return resxml;
            }
            WriteLog(Event);
            if (Event == "CLICK")//自定义菜单的CKICK方式
            {
                string EventKey = rootElement.SelectSingleNode("EventKey").InnerText;

                WriteLog(EventKey);
                if (EventKey == "bangding")//绑定用户
                {
                    if (ddsj.bangdingshu(FromUserName) == 5)
                    {
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[超过每个微信号可绑定用户限制！\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);

                        cn.Close();
                        return resxml;
                    }
                    //WriteLog(system_config.Rows[0]["shifoushuibiaohao"].ToString());
                    if (system_config.Rows[0]["shifoushuibiaohao"].ToString() == "False")//只支持绑定码
                    {
                        WriteLog(ddsj.shifouguanzhu(FromUserName));
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["ztgbdmhf"].ToString() + "\n\n" + system_config.Rows[0]["bangdingtishshuomingizuihou"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=2 where weixinghao='" + FromUserName + "'");

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);

                        cn.Close();
                        return resxml;

                    }
                    else//可支持绑定码和水表号+电话号码
                    {
                        WriteLog(ddsj.shifouguanzhu(FromUserName));
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[请回复数字【1】 " + system_config.Rows[0]["bdsbdhwzsm"].ToString() + "\n" + "请回复数字【2】 " + system_config.Rows[0]["bdssbhhdhumsm"].ToString() + "\n\n" + system_config.Rows[0]["bangdingtishshuomingizuihou"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        datacom.eccom("update guanzhuqingkuang set zhuixingbiaozhi=1 where weixinghao='" + FromUserName + "'");

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }
                }
                if (EventKey == "shuifei")//查水费
                {
                    //WriteLog(system_config.Rows[0]["shifoushuibiaohao"].ToString());
                    WriteLog(FromUserName);
                    string cxjg = ddsj.chashuifei(FromUserName);//通过微信号查水费
                    WriteLog(cxjg);
                    if (cxjg != "")//查到数据，直接返回
                    {

                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + cxjg + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";


                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }
                    else//未查到数据，看是否未绑定
                    {
                        //判断是否已绑定业务
                        sql = "select * from jibenzhiliao where weixinghao='" + FromUserName + "'";
                        //WriteLog(sql);
                        myCommand.CommandText = sql;
                        myCommand.Clone();
                        cn.Close();
                        cn.Open();
                        //WriteLog("开始执行"+sql);
                        SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        //WriteLog("执行完成" + sql);
                        if (reader.Read())
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[未找到相关数据" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;
                        }
                        else
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[未绑定！请点击相关菜单进行绑定" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                    }
                }
                if (EventKey == "tingshui")//查停水通知
                {
                    //WriteLog(system_config.Rows[0]["shifoushuibiaohao"].ToString());
                    WriteLog(FromUserName);
                    string cxjg = ddsj.chatingshui(FromUserName);//通过微信号查停水通知
                    WriteLog(FromUserName);
                    if (cxjg != "")//查到数据，直接返回
                    {

                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + cxjg + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";


                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }
                    else//未查到数据，看是否未绑定
                    {
                        //判断是否已绑定业务
                        sql = "select * from jibenzhiliao where weixinghao='" + FromUserName + "'";
                        //WriteLog(sql);
                        myCommand.CommandText = sql;
                        myCommand.Clone();
                        cn.Close();
                        cn.Open();
                        //WriteLog("开始执行"+sql);
                        SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        //WriteLog("执行完成" + sql);
                        if (reader.Read())
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您所在区域无停水信息" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;
                        }
                        else
                        {
                            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[未绑定！请点击相关菜单进行绑定" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                            yichuli = "yi";

                            System.Web.HttpContext.Current.Response.Write(resxml);
                            cn.Close();
                            return resxml;

                        }
                    }
                }
                if (EventKey == "suoyoutingshui")//查所有停水通知
                {
                    //WriteLog(system_config.Rows[0]["shifoushuibiaohao"].ToString());
                    WriteLog(FromUserName);
                    string cxjg = ddsj.chatingshuisy(FromUserName);//通过微信号查停水通知
                    WriteLog(FromUserName);
                    if (cxjg != "")//查到数据，直接返回
                    {

                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + cxjg + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";


                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }
                    else//未查到数据
                    {
                        //判断是否已绑定业务
                        //sql = "select * from jibenzhiliao where weixinghao='" + FromUserName + "'";
                        //WriteLog(sql);
                        //myCommand.CommandText = sql;
                        //myCommand.Clone();
                        //cn.Close();
                        //cn.Open();
                        //WriteLog("开始执行"+sql);
                        //SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        //WriteLog("执行完成" + sql);
                        //if (reader.Read())
                        //{
                        resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您所在区域无停水信息" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        yichuli = "yi";

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;
                        // }
                        //else
                        // {
                        //resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[未绑定！请点击相关菜单进行绑定" + "\n\n" + system_config.Rows[0]["weizhaodao"].ToString() + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";

                        //yichuli = "yi";

                        //System.Web.HttpContext.Current.Response.Write(resxml);
                        //cn.Close();
                        //return resxml;

                        // }
                    }
                }

                //if (EventKey == "suoyoutingshui")//返回动态链接

                //WriteLog(system_config.Rows[0]["shifoushuibiaohao"].ToString());
                WriteLog(FromUserName);

                //动态链接有两种，一种为多条记录，一种为一条记录，先判断
                cn.Close();
                cn.Open();
                sql = "select parentID from YeWuZiLiao where id=" + EventKey;
                myCommand.CommandText = sql;
                int count1 = Convert.ToInt32(myCommand.ExecuteScalar());
                WriteLog("记录数" + Convert.ToString(count1));
                if (count1 > 0)//业务资料,返回图文信息
                {

                    sql = "select id,mingcheng,substring(neirong,1,100) as nr,imgdir from YeWuZiLiao where id=" + EventKey;
                    //WriteLog(sql);
                    myCommand.CommandText = sql;
                    myCommand.Clone();
                    cn.Close();
                    cn.Open();
                    //WriteLog("开始执行"+sql);
                    SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                    if (reader.Read())
                    {//WriteLog("执行完成" + sql);
                        @resxml = "<xml>" +
                                  "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
                                  "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
                                  "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>" +
                                  "<MsgType><![CDATA[news]]></MsgType>" +
                                  "<ArticleCount>1</ArticleCount>" +
                                  "<Articles>" +
                                  "<item>" +
                                  "<Title><![CDATA[" + reader["mingcheng"].ToString() + "]]></Title> " +
                                  "<Description><![CDATA[" + reader["nr"].ToString() + "]]></Description>" +
                                  "<PicUrl><![CDATA[" + system_config.Rows[0]["urltou"].ToString() + system_config.Rows[0]["danweihao"].ToString() + reader["imgdir"].ToString().Substring(1, 300) + "]]></PicUrl>" +
                                  "<Url><![CDATA[" + system_config.Rows[0]["urltou"].ToString() + system_config.Rows[0]["danweihao"].ToString() + "/wap/yewuziliao.aspx?id=" + reader["id"].ToString() + "]]></Url>" +
                                  "</item></Articles></xml> ";

                        yichuli = "yi";

                        WriteLog(resxml);

                        System.Web.HttpContext.Current.Response.Write(resxml);
                        cn.Close();
                        return resxml;

                    }

                }
                else//业务标题,返回标题链接
                {
                    string jieguo = "";
                    sql = "select *  from YeWuZiLiao where parentID=" + EventKey;
                    myCommand.CommandText = sql;
                    myCommand.Clone();
                    cn.Close();
                    cn.Open();
                    //WriteLog("开始执行"+sql);
                    SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    //WriteLog("执行完成" + sql);
                    while (reader.Read())
                    {
                        @jieguo = jieguo + "<a href='" + system_config.Rows[0]["urltou"].ToString() + system_config.Rows[0]["danweihao"].ToString() + "/wap/yewuziliao.aspx?id=" + reader["id"].ToString() + "'>" + reader["mingcheng"].ToString() + "</a>\n\n";

                    }
                    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + jieguo + "\n\n" + system_config.Rows[0]["guanggao"].ToString() + "]]></Content></xml>";


                    yichuli = "yi";

                    System.Web.HttpContext.Current.Response.Write(resxml);
                    cn.Close();
                    return resxml;
                }





            }



        }

        if (yichuli == "wei") //发来数据无任何处理时从数据库中取得默认文字回复
        {

            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + system_config.Rows[0]["weizhaodao"].ToString() + "]]></Content></xml>";
            WriteLog(resxml);
            System.Web.HttpContext.Current.Response.Write(resxml);
            cn.Close();
            return resxml;

        }
        cn.Close();
        return resxml;

    }

    /// <summary>

    /// unix时间转换为datetime

    /// </summary>

    /// <param name="timeStamp"></param>

    /// <returns></returns>

    private DateTime UnixTimeToTime(string timeStamp)
    {

        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        long lTime = long.Parse(timeStamp + "0000000");

        TimeSpan toNow = new TimeSpan(lTime);

        return dtStart.Add(toNow);

    }

    /// <summary>

    /// datetime转换为unixtime

    /// </summary>

    /// <param name="time"></param>

    /// <returns></returns>

    private int ConvertDateTimeInt(System.DateTime time)
    {

        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        return (int)(time - startTime).TotalSeconds;

    }

    /// <summary>

    /// 写日志(用于跟踪)

    /// </summary>

    private void WriteLog(string strMemo)
    {

        string filename = Server.MapPath("~/") + "logs\\log.txt";

        if (!Directory.Exists(Server.MapPath("~/") + ("logs\\")))

            Directory.CreateDirectory("\\logs\\");

        StreamWriter sr = null;

        try
        {

            if (!File.Exists(filename))
            {

                sr = File.CreateText(filename);

            }

            else
            {

                sr = File.AppendText(filename);

            }

            sr.WriteLine(strMemo);

        }

        catch
        {

        }

        finally
        {

            if (sr != null)

                sr.Close();

        }

    }

}